<div id="storegoodsdetail">
    <el-container v-loading="loading">
        <el-main>
            <!-- 页面标题 -->
            <div class="page-header">
                <h2 class="page-title">@{{ isEditMode ? '编辑商品' : '商品发布' }}</h2>
            </div>

            <!-- 步骤条 -->
            <el-card class="mb-4">
                <el-steps :active="currentStep" finish-status="success" align-center>
                    <el-step title="基本信息" description="填写商品基本信息"></el-step>
                    <el-step title="规格参数" description="设置商品规格属性"></el-step>
                    <el-step title="商品详情" description="完善商品详情描述"></el-step>
                </el-steps>
            </el-card>

            <!-- 步骤内容 -->
            <div class="step-content">
                <!-- 第一步：基本信息 -->
                <el-card v-show="currentStep === 0" class="mb-4">
                    <!-- 商品分类 -->
                    <div class="form-section">
                        <h3 class="section-title">商品分类</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="商品分类:" required>
                                <el-select
                                    v-model="form.category_id_1"
                                    placeholder="请选择一级分类"
                                    @change="handleCategory1Change"
                                    style="width: 200px;"
                                >
                                    <el-option
                                        v-for="item in category1List"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                                <el-select
                                    v-model="form.category_id_2"
                                    placeholder="请选择二级分类"
                                    style="width: 200px; margin-left: 10px;"
                                >
                                    <el-option
                                        v-for="item in category2List"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>

                    <!-- 商品信息 -->
                    <div class="form-section">
                        <h3 class="section-title">商品信息</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="商品全称:" required>
                                <el-input v-model="form.title" placeholder="请输入商品全称" style="width: 400px;" />
                            </el-form-item>

                            <el-form-item label="商品简称:">
                                <el-input v-model="form.alias" placeholder="请输入商品简称" style="width: 400px;" />
                            </el-form-item>

                            <el-form-item label="商品单位:" required>
                                <el-input
                                    v-model="form.sku"
                                    placeholder="请输入商品单位(如:件、盒、箱)"
                                    style="width: 200px;"
                                />
                            </el-form-item>

                            <el-form-item label="排序:">
                                <el-input-number
                                    v-model="form.display_order"
                                    :min="0"
                                    :max="9999"
                                    placeholder="请输入排序值"
                                    controls-position="right"
                                />
                                <span class="form-hint">数值越大越靠前</span>
                            </el-form-item>
                        </el-form>
                    </div>

                    <!-- 商品图片与视频 -->
                    <div class="form-section">
                        <h3 class="section-title">商品图片与视频</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="商品主图:" required>
                                <div class="upload-wrapper">
                                    <el-upload
                                        class="upload-demo"
                                        action="/api/store/upload/image"
                                        :on-success="handleMainImageSuccess"
                                        :before-upload="beforeUpload"
                                        :show-file-list="false"
                                        :http-request="handleImageUploadRequest"
                                        :data="{ type: 'goods', attach: 'main' }"
                                    >
                                        <div v-if="!form.thumb" class="upload-area">
                                            <i class="el-icon-plus"></i>
                                            <div>上传主图</div>
                                        </div>
                                        <div v-else class="image-preview">
                                            <img :src="form.thumb" alt="主图" />
                                        </div>
                                    </el-upload>
                                    <el-button v-if="form.thumb" type="text" @click="form.thumb = ''">删除</el-button>
                                    <div class="upload-hint">建议尺寸640x640像素</div>
                                </div>
                            </el-form-item>

                            <el-form-item label="商品其他图片:">
                                <div class="image-list">
                                    <div v-for="(image, index) in form.thumb_url" :key="index" class="image-preview">
                                        <img :src="image" alt="其他图片" />
                                        <el-button type="text" class="delete-btn" @click="removeOtherImage(index)">
                                            <i class="el-icon-delete"></i>
                                        </el-button>
                                    </div>
                                    <el-upload
                                        v-if="form.thumb_url.length < 9"
                                        class="upload-demo"
                                        action="/api/store/upload/image"
                                        :on-success="handleOtherImageSuccess"
                                        :before-upload="beforeUpload"
                                        :show-file-list="false"
                                        :http-request="handleImageUploadRequest"
                                        :data="{ type: 'goods', attach: 'gallery' }"
                                    >
                                        <div class="upload-area">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </el-upload>
                                </div>
                                <div class="upload-hint">建议尺寸640x640像素, 最多上传9张</div>
                            </el-form-item>

                            <el-form-item label="商品视频:">
                                <div class="upload-wrapper">
                                    <el-upload
                                        class="upload-demo"
                                        action="/api/store/upload/file"
                                        :on-success="handleVideoSuccess"
                                        :before-upload="beforeVideoUpload"
                                        :show-file-list="false"
                                        :data="{ type: 'goods', attach: 'video' }"
                                    >
                                        <div v-if="!form.video_url" class="upload-area video-upload">
                                            <i class="el-icon-video-camera"></i>
                                            <div>上传视频</div>
                                        </div>
                                        <div v-else class="video-preview">
                                            <video :src="form.video_url" controls></video>
                                        </div>
                                    </el-upload>
                                    <el-button v-if="form.video_url" type="text" @click="form.video_url = ''">删除</el-button>
                                </div>
                            </el-form-item>
                        </el-form>
                    </div>

                    <!-- 销售设置 -->
                    <div class="form-section">
                        <h3 class="section-title">销售设置</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="价格设置:" required>
                                <div class="price-inputs">
                                    <div class="price-item">
                                        <label>市场价格</label>
                                        <el-input
                                            v-model="form.market_price"
                                            placeholder="0.00"
                                            class="price-input"
                                        >
                                            <template slot="prepend">¥</template>
                                        </el-input>
                                    </div>
                                    <div class="price-item">
                                        <label>现价</label>
                                        <el-input
                                            v-model="form.price"
                                            placeholder="0.00"
                                            class="price-input"
                                        >
                                            <template slot="prepend">¥</template>
                                        </el-input>
                                    </div>
                                    <div class="price-item">
                                        <label>成本价</label>
                                        <el-input
                                            v-model="form.cost_price"
                                            placeholder="0.00"
                                            class="price-input"
                                        >
                                            <template slot="prepend">¥</template>
                                        </el-input>
                                    </div>
                                </div>
                            </el-form-item>

                            <el-form-item label="库存数:" required>
                                <el-input-number
                                    v-model="form.stock"
                                    :min="0"
                                    placeholder="库存数量"
                                    style="width: 200px;"
                                />
                            </el-form-item>

                            <el-form-item label="减库存方式:">
                                <el-radio-group v-model="form.reduce_stock_method">
                                    <el-radio :label="0">下单减库存</el-radio>
                                    <el-radio :label="1">付款减库存</el-radio>
                                    <el-radio :label="2">永不减库存</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="是否上架:">
                                <el-switch
                                    v-model="form.status"
                                    :active-value="1"
                                    :inactive-value="0"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>

                <!-- 第二步：规格参数 -->
                <el-card v-show="currentStep === 1" class="mb-4">
                    <div class="form-section">
                        <h3 class="section-title">规格设置</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="是否启用规格属性:">
                                <el-switch
                                    v-model="form.has_option"
                                    @change="handleOptionChange"
                                    :active-value="1"
                                    :inactive-value="0"
                                />
                                <div class="option-hint">
                                    <p>1、启用商品规格后,商品的价格及库存以商品规格为准!</p>
                                    <p>2、每一种规格代表不同型号,例如颜色为一种规格,尺寸为一种规格,如果设置多规格,用户必须每一种规格都选择一个规格项,才能添加购物车或购买。</p>
                                </div>
                            </el-form-item>
                        </el-form>

                        <!-- 规格定义 -->
                        <div v-if="form.has_option" class="spec-section">
                            <h4 class="spec-section-title">商品规格</h4>
                            <div v-for="(spec, specIndex) in specs" :key="specIndex" class="spec-item">
                            <el-input 
                                    v-model="spec.title" 
                                    placeholder="规格名(如:颜色、尺寸)" 
                                    style="width: 150px;"
                                    class="spec-name-input"
                                ></el-input>
                                <div class="spec-values-container">
                                    <el-tag
                                        v-for="(value, valueIndex) in spec.items"
                                        :key="valueIndex"
                                        closable
                                        type="info"
                                        @close="removeSpecValue(specIndex, valueIndex)"
                                        class="spec-tag"
                                    >
                                        @{{ value.title }}
                                    </el-tag>
                                    <el-input
                                        v-show="spec.inputVisible"
                                        :ref="'saveTagInput' + specIndex"
                                        v-model="spec.inputValue"
                                        size="small"
                                        style="width: 100px;"
                                        @keyup.enter.native="handleInputConfirm(specIndex)"
                                        @blur="handleInputConfirm(specIndex)"
                                        class="spec-value-input"
                                    ></el-input>
                                    <el-button
                                        v-show="!spec.inputVisible"
                                        size="small"
                                        type="text"
                                        @click="showInput(specIndex)"
                                        class="add-spec-value-btn"
                                    >
                                        +添加规格值
                                    </el-button>
                                </div>
                                <el-button 
                                    type="danger" 
                                    size="small"
                                    @click="removeSpec(specIndex)"
                                    class="delete-spec-btn"
                                >
                                    删除规格
                                </el-button>
                            </div>

                            <div class="spec-actions">
                                <el-button type="primary" size="small" @click="addSpec">+新增规格</el-button>
                                <el-button size="small" @click="clearAllSpecs">清除全部规格</el-button>
                            </div>
                        </div>

                        <!-- 规格提示 -->
                        <div v-if="form.has_option && specs.length > 0 && specOptions.length === 0" class="spec-hint">
                            <i class="el-icon-warning"></i> 请为每个规格添加至少一个规格值，才能生成规格明细表格
                        </div>

                        <!-- 规格明细表格 -->
                        <div v-if="form.has_option && specs.length > 0 && specOptions.length > 0" class="spec-detail-section">
                            <h4 class="spec-section-title">规格明细</h4>
                            <div class="spec-table-wrapper">
                                <el-table :data="specOptions" border stripe style="width: 100%">
                                    <el-table-column
                                        v-for="spec in specs"
                                        :key="spec.title"
                                        :label="spec.title"
                                        width="100"
                                        align="center"
                                    >
                                        <template slot-scope="scope">
                                            <span class="spec-value-cell">@{{ scope.row[spec.title] }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" width="100" align="center">
                                        <template slot-scope="scope">
                                            <el-input-number 
                                                v-model="scope.row.stock" 
                                                :min="0" 
                                                size="mini" 
                                                :controls="false"
                                                style="width: 80px;" 
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="市场价格" width="110" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.market_price" 
                                                size="mini" 
                                                placeholder="0.00"
                                                style="width: 90px;"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="现价(元)" width="110" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.product_price" 
                                                size="mini" 
                                                placeholder="0.00"
                                                style="width: 90px;"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="成本价(元)" width="110" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.cost_price" 
                                                size="mini" 
                                                placeholder="0.00"
                                                style="width: 90px;"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="商品编码" width="130" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.goods_sn" 
                                                size="mini" 
                                                placeholder="编码"
                                                style="width: 110px;"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="重量(克)" width="110" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.weight" 
                                                size="mini" 
                                                placeholder="0"
                                                style="width: 90px;"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="体积(m³)" width="110" align="center">
                                        <template slot-scope="scope">
                                            <el-input 
                                                v-model="scope.row.volume" 
                                                size="mini" 
                                                placeholder="0"
                                                style="width: 90px;"
                                            />
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <div class="spec-summary">
                                数量:@{{ specOptions.length }}条; 建议最多不超过100条
                            </div>
                        </div>
                    </div>
                </el-card>

                <!-- 第三步：商品详情 -->
                <el-card v-show="currentStep === 2" class="mb-4">
                    <div class="form-section">
                        <h3 class="section-title">商品详情</h3>
                        <el-form :model="form" label-width="120px">
                            <el-form-item label="商品简述:">
                                <el-input
                                    v-model="form.description"
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入商品简述"
                                    style="width: 600px;"
                                />
                            </el-form-item>

                            <el-form-item label="商品详情:">
                                <div style="width: 800px;">
                                <textarea class="tinymce-textarea" :id="tinymceId"></textarea>
                                    <div class="form-hint">提示: 支持HTML格式,可以使用富文本编辑器</div>
                                </div>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </div>

            <!-- 步骤操作按钮 -->
            <el-card class="step-actions">
                <el-button @click="handleCancel">取消</el-button>
                <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
                <el-button
                    v-if="currentStep < 2"
                    type="primary"
                    @click="nextStep"
                    :disabled="!canNextStep"
                >
                    下一步
                </el-button>
                <el-button
                    v-if="currentStep === 2"
                    type="primary"
                    @click="handlePublish"
                    :loading="publishing"
                >
                    @{{ isEditMode ? '保存修改' : '发布商品' }}
                </el-button>
            </el-card>
        </el-main>
    </el-container>
</div>

<script>
      const plugins = [
 `advlist anchor autolink autosave code codesample colorpicker colorpicker
  contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime
  legacyoutput link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace
  spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount`
  ];
  const toolbar = [
    `bold italic underline strikethrough alignleft aligncenter
  alignright outdent indent  blockquote undo redo removeformat code`,
    `hr bullist numlist link image charmap	 preview anchor pagebreak
    fullscreen insertdatetime media table forecolor backcolor`
  ];
new Vue({
    el: '#storegoodsdetail',
    data() {
        return {
            toolbar:[],
            currentStep: 0,
            loading: false,
            publishing: false,
            isEditMode: false,
            goodsId: null,

            // 表单数据
            form: {
                title: '',
                alias: '',
                sku: '',
                thumb: '',
                thumb_url: [],
                video_url: '',
                category_id_1: '',
                category_id_2: '',
                market_price: '',
                price: '',
                cost_price: '',
                stock: 0,
                reduce_stock_method: 0,
                status: 1,
                has_option: 0,
                display_order: 0,
                description: '',
                content: ''
            },

            // 分类数据
            category1List: [],
            category2List: [],

            // 规格数据
            specs: [],
            specOptions: [],
            tinymceId: this.id || 'vue-tinymce-' + +new Date()
        };
    },

    computed: {
        // 判断是否可以进入下一步
        canNextStep() {
            if (this.currentStep === 0) {
                // 第一步：基本信息验证
                return (
                    this.form.title &&
                    this.form.category_id_1 &&
                    this.form.price &&
                    this.form.stock >= 0 &&
                    this.form.thumb
                );
            } else if (this.currentStep === 1) {
                // 第二步：规格参数验证
                if (this.form.has_option && this.specs.length > 0) {
                    return this.specs.every(spec => spec.title && spec.items.length > 0);
                }
                return true;
            }
            return true;
        }
    },

    mounted() {
        this.initPage();
        this.loadCategories();
    },

    methods: {
        // 初始化页面
        initPage() {
            const urlParams = new URLSearchParams(window.location.search);
            const goodsId = urlParams.get('id');
            if (goodsId) {
                this.isEditMode = true;
                this.goodsId = goodsId;
                this.loadGoodsDetail();
            }
        },

        // 加载商品详情（编辑模式）
        async loadGoodsDetail() {
            this.loading = true;
            try {
                const response = await window.api.post('/admin/store-goods/get-detail', {
                    goods_id: this.goodsId
                });

                if (response && response.result === 1) {
                    const goods = response.data.goods;
                    
                    // 填充表单数据
                    this.form = {
                        title: goods.title || '',
                        alias: goods.alias || '',
                        sku: goods.sku || '',
                        thumb: goods.thumb || '',
                        thumb_url: goods.thumb_url ? JSON.parse(goods.thumb_url) : [],
                        video_url: goods.video_url || '',
                        category_id_1: goods.category_id_1 || '',
                        category_id_2: goods.category_id_2 || '',
                        market_price: goods.market_price || '',
                        price: goods.price || '',
                        cost_price: goods.cost_price || '',
                        stock: goods.stock || 0,
                        reduce_stock_method: goods.reduce_stock_method || 0,
                        status: goods.status || 1,
                        has_option: goods.has_option || 0,
                        display_order: goods.display_order || 0,
                        description: goods.description || '',
                        content: goods.content || ''
                    };

                    // 处理规格数据
                    if (goods.has_option && response.data.specs) {
                        this.specs = response.data.specs.map(spec => ({
                            id: spec.id,
                            title: spec.title,
                            items: spec.items || [],
                            inputVisible: false,
                            inputValue: ''
                        }));

                        // 处理规格选项
                        if (response.data.options && response.data.options.length > 0) {
                            this.specOptions = response.data.options.map(option => {
                                const specObj = {};
                                
                                // 解析 specs JSON
                                if (option.specs) {
                                    try {
                                        const specs = typeof option.specs === 'string' 
                                            ? JSON.parse(option.specs) 
                                            : option.specs;
                                        
                                        specs.forEach(spec => {
                                            const specAttr = this.specs.find(s => s.title === spec.spec_title || s.id === spec.spec_id);
                                            if (specAttr) {
                                                const specItem = specAttr.items.find(item => 
                                                    item.id === spec.spec_item_id || item.title === spec.title
                                                );
                                                if (specItem) {
                                                    specObj[specAttr.title] = specItem.title;
                                                }
                                            }
                                        });
                                    } catch (e) {
                                        console.error('解析规格数据失败:', e);
                                    }
                                }

                                return {
                                    ...specObj,
                                    stock: option.stock || 0,
                                    market_price: option.market_price || '',
                                    product_price: option.product_price || '',
                                    cost_price: option.cost_price || '',
                                    goods_sn: option.goods_sn || '',
                                    weight: option.weight || '',
                                    volume: option.volume || ''
                                };
                            });
                        } else {
                            this.generateSpecOptions();
                        }
                    }

                    // 加载对应的分类
                    if (goods.category_id_1) {
                        await this.loadCategory2List(goods.category_id_1);
                    }
                } else {
                    this.$message.error(response.msg || '加载商品详情失败');
                }
            } catch (error) {
                console.error('加载商品详情失败', error);
                this.$message.error('加载商品详情失败');
            } finally {
                this.loading = false;
            }
        },

        // 加载一级分类
        async loadCategories() {
            try {
                const response = await window.api.post('/api/store/goods/getCategories', {
                    param: { level: 1 },
                    organid: null
                });
                if (response && response.result === 1) {
                    this.category1List = response.data.list || [];
                }
            } catch (error) {
                console.error('加载分类失败', error);
                this.$message.error('加载分类失败');
            }
        },

        // 一级分类变化
        async handleCategory1Change(value) {
            this.form.category_id_2 = '';
            this.category2List = [];
            if (value) {
                await this.loadCategory2List(value);
            }
        },

        // 加载二级分类
        async loadCategory2List(parentId) {
            try {
                const response = await window.api.post('/api/store/goods/getCategories', {
                    param: { level: 2, parent_id: parentId },
                    organid: null
                });
                if (response && response.result === 1) {
                    this.category2List = response.data.list || [];
                }
            } catch (error) {
                console.error('加载二级分类失败', error);
                this.$message.error('加载二级分类失败');
            }
        },

        // 上传前验证
        beforeUpload(file) {
            const isImage = file && file.type && file.type.startsWith('image/');
            const isLt10M = file && file.size / 1024 / 1024 < 10;

            if (!isImage) {
                this.$message.error('只能上传图片文件!');
                return false;
            }
            if (!isLt10M) {
                this.$message.error('图片大小不能超过 10MB!');
                return false;
            }
            return true;
        },

        async handleImageUploadRequest(options) {
            const {
                file,
                data,
                action,
                onSuccess,
                onError,
                onProgress
            } = options;

            const uploadUrl = action || '/api/store/upload/image';
            const axiosInstance = (window && (window.axios || window.Axios)) || (typeof axios !== 'undefined' ? axios : null);

            if (!axiosInstance) {
                const error = new Error('上传组件依赖的 axios 未加载');
                onError && onError(error);
                this.$message.error(error.message);
                return;
            }

            try {
                const compressedFile = await this.compressImage(file, {
                    maxWidth: 1280,
                    maxHeight: 1280,
                    quality: 0.8
                });

                const formData = new FormData();
                if (data && typeof data === 'object') {
                    Object.keys(data).forEach(key => {
                        const value = data[key];
                        if (value !== undefined && value !== null) {
                            formData.append(key, value);
                        }
                    });
                }
                formData.append('file', compressedFile, compressedFile.name || file.name);

                const config = {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    onUploadProgress: (event) => {
                        if (event.total > 0 && typeof onProgress === 'function') {
                            const percent = Math.round((event.loaded / event.total) * 100);
                            onProgress({ percent });
                        }
                    }
                };

                const response = await axiosInstance.post(uploadUrl, formData, config);
                if (typeof onSuccess === 'function') {
                    onSuccess(response, compressedFile);
                }
            } catch (error) {
                console.error('upload error', error);
                if (typeof onError === 'function') {
                    onError(error);
                }
                this.$message.error(error.message || '图片上传失败');
            }
        },

        async compressImage(file, options = {}) {
            const { maxWidth = 1280, maxHeight = 1280, quality = 0.8 } = options;

            if (!file || !file.type || !file.type.startsWith('image/') || file.type === 'image/gif') {
                return file;
            }

            return new Promise((resolve, reject) => {
                const image = new Image();
                const objectUrl = URL.createObjectURL(file);

                image.onload = () => {
                    let { width, height } = image;
                    let targetWidth = width;
                    let targetHeight = height;

                    const scale = Math.min(maxWidth / width, maxHeight / height);
                    if (scale < 1) {
                        targetWidth = Math.round(width * scale);
                        targetHeight = Math.round(height * scale);
                    }

                    const canvas = document.createElement('canvas');
                    canvas.width = targetWidth;
                    canvas.height = targetHeight;
                    const ctx = canvas.getContext('2d');
                    ctx.clearRect(0, 0, targetWidth, targetHeight);
                    ctx.drawImage(image, 0, 0, targetWidth, targetHeight);

                    const mimeType = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
                    const qualityValue = mimeType === 'image/png' ? undefined : quality;

                    canvas.toBlob(
                        blob => {
                            URL.revokeObjectURL(objectUrl);
                            if (!blob) {
                                reject(new Error('图片压缩失败'));
                                return;
                            }
                            const compressedFile = new File([blob], file.name || 'upload.jpg', {
                                type: mimeType,
                                lastModified: Date.now()
                            });
                            if (file.uid) {
                                compressedFile.uid = file.uid;
                            }
                            resolve(compressedFile);
                        },
                        mimeType,
                        qualityValue
                    );
                };

            image.onerror = () => {
                URL.revokeObjectURL(objectUrl);
                reject(new Error('图片加载失败'));
            };

            image.src = objectUrl;
        });
        },

        // 视频上传前验证
        beforeVideoUpload(file) {
            const isVideo = file.type.startsWith('video/');
            const isLt50M = file.size / 1024 / 1024 < 50;

            if (!isVideo) {
                this.$message.error('只能上传视频文件!');
                return false;
            }
            if (!isLt50M) {
                this.$message.error('视频大小不能超过 50MB!');
                return false;
            }
            return true;
        },

        // 主图上传成功
        handleMainImageSuccess(response) {
            if(!response){
                return
            }
            if (response.result === 1) {
                this.form.thumb = response.data.url;
                this.$message.success('主图上传成功');
            } else {
                this.$message.error(response.msg || '上传失败');
            }
        },

        // 其他图片上传成功
        handleOtherImageSuccess(response) {
            if(!response){
                return
            }
            if (response.result === 1) {
                this.form.thumb_url.push(response.data.url);
                this.$message.success('图片上传成功');
            } else {
                this.$message.error(response.msg || '上传失败');
            }
        },

        // 删除其他图片
        removeOtherImage(index) {
            this.form.thumb_url.splice(index, 1);
        },

        // 视频上传成功
        handleVideoSuccess(response) {
            if (response.result === 1) {
                this.form.video_url = response.data.url;
                this.$message.success('视频上传成功');
            } else {
                this.$message.error(response.msg || '上传失败');
            }
        },

        // 规格开关变化
        handleOptionChange(value) {
            if (!value) {
                this.specs = [];
                this.specOptions = [];
            }
        },

        // 添加规格
        addSpec() {
            let data={
                title: '',
                items: [],
                inputVisible: false,
                inputValue: ''
            };
            this.$set(this.specs, this.specs.length, data);
            console.log(this.specs);
        },

        // 删除规格
        removeSpec(index) {
            this.specs.splice(index, 1);
            this.generateSpecOptions();
        },

        // 显示输入框
        showInput(specIndex) {
            this.specs[specIndex].inputVisible = true;
            this.$nextTick(() => {
                const refName = 'saveTagInput' + specIndex;
                const input = this.$refs[refName];
                if (input) {
                    // input 可能是数组或单个元素
                    const el = Array.isArray(input) ? input[0] : input;
                    if (el && el.focus) {
                        el.focus();
                    }
                }
            });
        },

        // 确认输入
        handleInputConfirm(specIndex) {
            const inputValue = this.specs[specIndex].inputValue;
            if (inputValue) {
                this.specs[specIndex].items.push({ title: inputValue });
            }
            this.specs[specIndex].inputVisible = false;
            this.specs[specIndex].inputValue = '';
            this.generateSpecOptions();
        },

        // 删除规格值
        removeSpecValue(specIndex, valueIndex) {
            this.specs[specIndex].items.splice(valueIndex, 1);
            this.generateSpecOptions();
        },

        // 清除所有规格
        clearAllSpecs() {
            this.specs = [];
            this.specOptions = [];
        },

        // 生成规格选项
        generateSpecOptions() {
            if (this.specs.length === 0) {
                this.specOptions = [];
                return;
            }

            // 检查是否所有规格都有规格值
            const hasEmptySpec = this.specs.some(spec => !spec.items || spec.items.length === 0);
            if (hasEmptySpec) {
                this.specOptions = [];
                return;
            }

            // 生成所有可能的组合
            const combinations = this.generateCombinations(this.specs);
            this.specOptions = combinations.map(combo => ({
                ...combo,
                stock: 0,
                market_price: '',
                product_price: '',
                cost_price: '',
                goods_sn: '',
                weight: '',
                volume: ''
            }));
        },

        // 生成组合
        generateCombinations(specs) {
            if (specs.length === 0) return [];
            
            // 过滤出有规格值的规格
            const validSpecs = specs.filter(spec => spec.items && spec.items.length > 0);
            if (validSpecs.length === 0) return [];
            
            if (validSpecs.length === 1) {
                return validSpecs[0].items.map(item => ({
                    [validSpecs[0].title]: item.title
                }));
            }

            const result = [];
            const generate = (index, current) => {
                if (index === validSpecs.length) {
                    result.push({ ...current });
                    return;
                }

                if (validSpecs[index].items && validSpecs[index].items.length > 0) {
                    validSpecs[index].items.forEach(item => {
                        generate(index + 1, { ...current, [validSpecs[index].title]: item.title });
                    });
                }
            };

            generate(0, {});
            return result;
        },

        // 下一步
        async nextStep() {
            if (!this.canNextStep) {
                this.$message.warning('请完成必填信息');
                return;
            }

            if (this.currentStep === 0) {
                // 保存基本信息
                try {
                    await this.saveBasicInfo();
                    this.currentStep++;
                } catch (error) {
                    this.$message.error('保存失败，请重试');
                }
            } else if (this.currentStep === 1) {
                // 保存规格信息
                if (this.form.has_option && this.specs.length > 0) {
                    try {
                        await this.saveSpecsInfo();
                        this.currentStep++;
                        this.$nextTick(() => {
                            this.initTinymce();
                        });
                    } catch (error) {
                        this.$message.error('保存规格失败，请重试');
                    }
                } else {
                    this.currentStep++;
                    this.$nextTick(() => {
                            this.initTinymce();
                        });
                }
            }
        },

        // 上一步
        prevStep() {
            if (this.currentStep > 0) {
                this.currentStep--;
            }
        },

        // 保存基本信息
        async saveBasicInfo() {
            const basicData = {
                goods_id: this.goodsId,
                title: this.form.title,
                alias: this.form.alias,
                sku: this.form.sku,
                thumb: this.form.thumb,
                thumb_url: this.form.thumb_url,
                video_url: this.form.video_url,
                category_id_1: this.form.category_id_1,
                category_id_2: this.form.category_id_2,
                market_price: this.form.market_price,
                price: this.form.price,
                cost_price: this.form.cost_price,
                stock: this.form.stock,
                reduce_stock_method: this.form.reduce_stock_method,
                status: this.form.status,
                display_order: this.form.display_order,
                has_option: 0 // 第一步暂时设为无规格
            };

            const response = await window.api.post('/admin/store-goods/update', basicData);
            if (response.result === 1) {
                this.$message.success('基本信息保存成功');
            } else {
                throw new Error(response.msg || '保存失败');
            }
        },

        // 保存规格信息
        async saveSpecsInfo() {
            if (!this.goodsId) {
                throw new Error('商品ID不存在，请先保存基本信息');
            }

            const specData = {
                goods_id: this.goodsId,
                has_option: this.form.has_option,
                specs: this.specs.map(spec => ({
                    title: spec.title,
                    items: spec.items.map(item => ({
                        title: item.title
                    }))
                })),
                options: this.specOptions.map(option => {
                    // 构建规格组合数据
                    const specs = [];

                    // 遍历每个规格属性，找到对应的规格值
                    this.specs.forEach(spec => {
                        if (option[spec.title]) {
                            // 找到对应的规格项
                            const specItem = spec.items.find(
                                item => item.title === option[spec.title]
                            );
                            if (specItem) {
                                specs.push({
                                    spec_id: spec.id || null,
                                    spec_title: spec.title,
                                    spec_item_id: specItem.id || null,
                                    title: specItem.title
                                });
                            }
                        }
                    });

                    return {
                        ...option,
                        specs: specs, // 添加规格组合数据
                        // 确保数值类型字段正确
                        stock: parseInt(option.stock) || 0,
                        market_price: parseFloat(option.market_price) || 0,
                        product_price: parseFloat(option.product_price) || 0,
                        cost_price: parseFloat(option.cost_price) || 0,
                        weight: parseFloat(option.weight) || 0,
                        volume: parseFloat(option.volume) || 0,
                        goods_sn: option.goods_sn || ''
                    };
                })
            };

            const response = await window.api.post('/admin/store-goods/update-specs', specData);
            if (response && response.result === 1) {
                this.$message.success('规格信息保存成功');
            } else {
                throw new Error(response.msg || '规格保存失败');
            }
        },

        // 发布商品
        async handlePublish() {
            this.publishing = true;
            this.form.content=this.getContent();
            try {
                const updateData = {
                    goods_id: this.goodsId,
                    description: this.form.description,
                    content: this.form.content
                };

                const response = await window.api.post('/admin/store-goods/update', updateData);
                
                if (response && response.result === 1) {
                    this.$message.success(this.isEditMode ? '商品更新成功' : '商品发布成功');
                    setTimeout(() => {
                        window.location.href = '/admin/store-goods';
                    }, 1000);
                } else {
                    this.$message.error(response.msg || '保存失败');
                }
            } catch (error) {
                console.error('保存失败', error);
                this.$message.error('保存失败');
            } finally {
                this.publishing = false;
            }
        },

        // 取消
        handleCancel() {
            window.location.href = '/admin/store-goods';
        },
        initTinymce() {
        const _this = this
        console.log(this.tinymceId,'111');
        window.tinymce.init({
          selector: `#${this.tinymceId}`,
          width: this.width,
          height: this.height,
          language: 'zh_CN',
          body_class: 'panel-body ',
          object_resizing: false,
          toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
          menubar: false,
          plugins: plugins,
          end_container_on_empty_block: true,
          powerpaste_word_import: 'clean',
          code_dialog_height: 450,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square',
          advlist_number_styles: 'default',
          imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
          default_link_target: '_blank',
          link_title: false,
          init_instance_callback: editor => {
            if (_this.value) {
              editor.setContent(_this.value)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp SetContent', () => {
              this.hasChange = true
              this.$emit('input', editor.getContent())
            })
          }
        })
        setTimeout(() => {
            this.setContent(this.form.content);
        }, 1000);
      },
      destroyTinymce() {
        if (window.tinymce.get(this.tinymceId)) {
          window.tinymce.get(this.tinymceId).destroy()
        }
      },
      setContent(value) {
        window.tinymce.get(this.tinymceId).setContent(value)
      },
      getContent() {
        return window.tinymce.get(this.tinymceId).getContent()
      },
    }
});
</script>

<style scoped>
.page-header {
    margin-bottom: 20px;
}

.page-title {
    font-size: 24px;
    font-weight: bold;
}

.mb-4 {
    margin-bottom: 16px;
}

.form-section {
    margin-bottom: 30px;
}

.form-section:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #303133;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
}

.form-hint {
    margin-left: 10px;
    font-size: 12px;
    color: #999;
}

/* 上传区域样式 */
.upload-wrapper {
    display: inline-block;
}

.upload-area {
    width: 120px;
    height: 120px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8c939d;
    transition: all 0.3s;
}

.upload-area:hover {
    border-color: #409eff;
    color: #409eff;
}

.upload-area i {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-hint {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
}

.image-preview {
    position: relative;
    display: inline-block;
    margin-right: 10px;
    margin-bottom: 10px;
}

.image-preview img {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

.image-preview .delete-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    border: none;
    padding: 5px;
    border-radius: 2px;
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.video-upload {
    width: 200px;
    height: 120px;
}

.video-preview video {
    width: 200px;
    height: 120px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

/* 价格输入框样式 */
.price-inputs {
    display: flex;
    gap: 20px;
    align-items: flex-end;
}

.price-item {
    display: flex;
    flex-direction: column;
}

.price-item label {
    font-size: 12px;
    color: #606266;
    margin-bottom: 5px;
}

.price-input {
    width: 150px;
}

/* 规格相关样式 */
.option-hint {
    margin-top: 10px;
    padding: 12px 15px;
    background: #f0f9ff;
    border-left: 3px solid #409eff;
    border-radius: 4px;
    font-size: 13px;
    color: #606266;
    line-height: 1.8;
}

.spec-hint {
    margin-top: 20px;
    padding: 12px 15px;
    background: #fff3e0;
    border-left: 3px solid #ff9800;
    border-radius: 4px;
    font-size: 14px;
    color: #e65100;
    text-align: center;
}

.spec-hint i {
    margin-right: 5px;
}

.option-hint p {
    margin: 0 0 5px 0;
}

.option-hint p:last-child {
    margin-bottom: 0;
}

.spec-section {
    margin-top: 20px;
    padding: 20px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
}

.spec-section-title {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #303133;
    padding-bottom: 10px;
    border-bottom: 2px solid #409eff;
}

.spec-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 15px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    gap: 15px;
}

.spec-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.spec-name-input {
    flex-shrink: 0;
}

.spec-values-container {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    min-height: 32px;
}

.spec-tag {
    margin: 0;
}

.spec-value-input {
    margin: 0;
}

.add-spec-value-btn {
    padding: 5px 15px;
    color: #409eff;
    font-size: 13px;
}

.add-spec-value-btn:hover {
    color: #66b1ff;
}

.delete-spec-btn {
    flex-shrink: 0;
}

.spec-actions {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px dashed #e4e7ed;
    display: flex;
    gap: 10px;
}

.spec-detail-section {
    margin-top: 30px;
}

.spec-table-wrapper {
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
}

.spec-value-cell {
    font-weight: 500;
    color: #606266;
}

.spec-summary {
    margin-top: 12px;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
    font-size: 13px;
    color: #606266;
    text-align: center;
}

/* 步骤操作按钮 */
.step-actions {
    text-align: center;
    padding: 20px;
}

.step-actions .el-button {
    margin: 0 10px;
}
</style>

